<template>
  <div class="dish-management">

    <!-- 菜品列表 -->
    <div class="dish-list">
      <h2>菜品列表</h2>
      <div class="scroll-container">
        <ul>
        <!-- 固定标题 -->
        <li class="dish-list-header">
          <span class="dish-name">菜品名称</span>
          <span class="dish-name">

            <button @click="viewAllFeedback()" style="margin-right: 30px;">查看所有反馈</button>
            <button @click="getDeletedDishes()">
              {{ showingDeletedDishes ? '回到当前菜品' : '查看历史菜品' }}
            </button>

          </span>

        </li>
        <li v-for="dish in dishes" :key="dish.dish_id">
          <span class="dish-name">{{ dish.name }}</span>
          <div class="actions">
            <button v-if="showingDeletedDishes" @click="restoreDish(dish)" style="margin-right: 72px;">恢复</button>

            <template v-else>

            <button @click="viewFeedback(dish)">查看反馈</button> <!-- Feedback button -->

            <button @click="editDish(dish)">编辑</button>
          <button @click="deleteDish(dish)">删除</button>
          <select v-model="dish.is_on_shelf" @change="updateShelfStatus(dish)">
            <option value="on">上架</option>
            <option value="off">下架</option>
          </select>
            </template>

          </div>
        </li>
      </ul>
      </div>
    </div>

    <!-- 添加/编辑菜品表单 -->
    <div class="dish-form">
      <h2>添加新菜品</h2>
      <form @submit.prevent="submitDish">
        <input v-model="form.name" type="text" placeholder="菜品名称" />
        <textarea v-model="form.description" placeholder="菜品描述"></textarea>
        <a>上传菜品图片</a> <input type="file" @change="handleFileUpload" />

        <select v-model="form.is_on_shelf">
          <option value="on">上架</option>
          <option value="off">下架</option>
        </select>

        <button type="submit">{{ editingDish ? '更新' : '添加' }}</button>

      </form>
    </div>
    <dish-edit-card @update-success="handleUpdateSuccess"
        v-if="showEditModal"
        :dish="editingDish"
        @close="showEditModal = false"
    ></dish-edit-card>

    <dish-feedback-card
        v-if="showFeedbackModal"
        :dish="selectedDishForFeedback"
        @close="showFeedbackModal = false"
    ></dish-feedback-card>

    <dish-all-feedback-card
        v-if="showAllFeedbackModal"
        :dishes="dishes"
        @close="showAllFeedbackModal = false"
    ></dish-all-feedback-card>

  </div>


</template>

<script>
import { getAllDishes, getDeletedDishes, addNewDish, updateDish } from '@/api/dishes';
import DishEditCard from '../../components/DishEditCard.vue'; // Import the DishEditCard component
import DishFeedbackCard from '../../components/DishFeedbackCard.vue'; // Adjust the path as necessary
import DishAllFeedbackCard from '../../components/DishAllFeedbackCard.vue'; // Adjust the path as necessary
import { uploadImage } from '@/api/utils';

export default {
  components: {
    DishEditCard,
    DishFeedbackCard,
    DishAllFeedbackCard
  },
  data() {
    return {
      dishes: [],
      form: { name: '', description: '', imageUrl: '', is_on_shelf: 'on', is_deleted: 'no' },
      editingDish: null,
      selectedFile: null,
      showEditModal: false,
      showFeedbackModal: false,
      showAllFeedbackModal: false,
      selectedDishForFeedback: null,
      showingDeletedDishes: false,

    };
  },
  methods: {
    handleUpdateSuccess() {
      // 调用 fetchDishes 方法来刷新菜品列表
      this.fetchDishes();
    },

    async restoreDish(dish) {
      try {
        dish.is_deleted = 'no';  // 更改菜品的删除状态
        await updateDish(dish.dish_id, dish); // 调用更新菜品的API
        this.getDeletedDishes(); // 重新获取已删除的菜品列表
      } catch (error) {
        console.error(error);
      }
    },

    async getDeletedDishes() {
      this.showingDeletedDishes = !this.showingDeletedDishes;
      try {
        let response;
        if (this.showingDeletedDishes) {
          response = await getDeletedDishes();
        } else {
          response = await getAllDishes();
        }
        this.dishes = response.data;
      } catch (error) {
        console.error(error);
      }
    },

    async fetchDishes() {
      try {
        const response = await getAllDishes();
        this.dishes = response.data;
      } catch (error) {
        console.error(error);
      }
    },
    editDish(dish) {
      this.editingDish = dish;
      this.showEditModal = true;

    },
    viewFeedback(dish) {
      this.selectedDishForFeedback = dish;
      this.showFeedbackModal = true;
    },


    viewAllFeedback() {
      this.showAllFeedbackModal = true;
    },

    async deleteDish(dish) {
      const confirmation = confirm('确定要删除这个菜品吗？');
      if (!confirmation) {
        return;
      }
      this.loading = true;
      try {
        console.log('111TTTEEST'+ dish)
        dish.is_deleted = 'yes';
        console.log('222TTTEEST'+ dish)
        await updateDish(dish.dish_id, dish);
        await this.fetchDishes(); // 重新获取菜品列表
      } catch (error) {
        console.error(error);
      }
    },
    async handleFileUpload(event) {
      this.selectedFile = event.target.files[0];
      try {
        const formData = new FormData();
        formData.append('file', this.selectedFile);

        // 获取前端上传的文件名
        const fileName = this.selectedFile.name;

        // 执行上传操作
        await uploadImage(formData);

        // 拼接路径前缀和图片名
        this.form.image_url = `/images/dishes/${fileName}`;

      } catch (error) {
        console.error(error);
      }
    },

    async updateShelfStatus(dish) {
      try {
        console.log('TESTA'+ dish.is_on_shelf)

        console.log(dish)

        await updateDish(dish.dish_id, dish);
        // You can add any additional handling you need here, such as displaying a success message.
      } catch (error) {
        console.error(error);
        // Handle errors here, such as displaying an error message to the user.
      }
    },

    async submitDish() {
      const dishData = {
        name: this.form.name,
        price: this.form.price,
        description: this.form.description,
        image_url: this.form.image_url,
        is_on_shelf: this.form.is_on_shelf,
        is_deleted: this.form.is_deleted
      };

      try {
        let response;
        if (this.editingDish) {
          response = await updateDish(this.editingDish.dish_id, dishData);
        } else {
          response = await addNewDish(dishData);
        }

        // Check for success response
        if (response && response.data) {
          alert(response.data.message || '菜品添加成功');
        } else {
          alert('Dish submission failed');
        }

        this.resetForm();
        await this.fetchDishes();
      } catch (error) {
        // Handle errors
        if (error.response && error.response.data) {
          alert(error.response.data.message || '菜品添加失败');
        } else {
          alert('菜品添加失败');
        }
        console.error('Error during dish submission', error);
      }
    },

    resetForm() {
      this.form = { name: '', price: '', description: '', imageUrl: '' };
      this.selectedFile = null;
      this.editingDish = null;
    }
  },
  mounted() {
    this.fetchDishes();
  },
};
</script>

<style scoped>
.dish-management {
  height: 85vh; /* 设置一个最大高度 */

  font-family: 'Arial', sans-serif;
  display: flex;
  gap: 20px;
  margin: 0 auto;
  max-width: 1200px;
  padding: 20px;
}

.dish-management h1,
.dish-management h2 {
  color: #333;
  text-align: center;
}

.dish-list,
.dish-form {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  flex: 1;
}

.scroll-container {
  max-height: 72vh; /* 设置一个最大高度 */
  overflow-y: auto; /* 添加滚动 */
  margin-right: -7px; /* 向右移动，为滚动条预留空间 */
  padding-right: 7px; /* 添加右内边距，等于滚动条的宽度 */
}
.dish-list ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.dish-list li {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  padding:1px;
}
.dish-list .actions {
  display: flex;
  gap: 10px;
}

.dish-list .dish-name {
  /* 这里添加您想要的样式 */
  font-weight: bold; /* 例如，加粗字体 */
  color: #333; /* 例如，设置字体颜色 */
  text-align: center;
  display: block; /* 使span表现得像块级元素 */
  width: 50%;
}


.dish-list button {
  background-color: #93bdd8;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  padding: 10px 15px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin-top: 5px;
  margin-bottom: 5px;
  padding:5px;
}

.dish-list button:hover {
  background-color: #A4D3F1;
}

.dish-list select {
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
  margin-top: 5px;
  margin-bottom: 5px;
  font-size: 14px;

}

.dish-form input[type="text"]{
  display: block;
  width: 100%;
  padding: 10px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;

}
.dish-form select {
  width: auto;
  padding: 10px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 14px;

}

.dish-form textarea {
  width: 100%;
  height: 40vh;
  padding: 10px;
  margin: 10px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 14px;
}


.dish-form button {
  display: block;
  width: 100%;
  background-color: #93bdd8;
  color: white;
  padding: 14px 20px;
  margin: 10px auto; /* 上下保持10px，左右自动，实现居中 */
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold; /* 例如，加粗字体 */

}

.dish-form button:hover {
  background-color: #A4D3F1;
}

input[type="file"] {
  margin-top: 15px;
  font-size: 14px;

}



.dish-list-header {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 100;
}

.dish-list-header span, .dish-list li span {
  display: inline-block;
  /* 根据需要调整宽度 */
  width: 120px; /* 例如，设置为120px */
}


</style>

